import React, { useState, useEffect } from 'react'
import { Col, Form, Input, Button, Table, message, Modal, Select, } from 'antd'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import RenderButtom from '@/components/RenderButton'
import SearchBox from '@/components/SearchBox'
import {
  getSingleList,
  startGoodsRef,
  settingPlans,
  distributionPlanName,
  goodsCatalog,
} from '@/services/distribution/setting'

const { Option } = Select
const hasSearchBtn = JSON.parse(localStorage.getItem('hasSearchBtn'))

const columns = [
  {
    title: '排序',
    dataIndex: 'sort',
    key: 'sort',
    render(text, record, index){
      return <div>{index + 1}</div>
    }
  },
  {
    title: '商品名称',
    dataIndex: 'goodsName',
    key: 'goodsName',
    render(text, record){
      return <div><img src={record.imageUrl} style={{width: 40}} />{text}</div>
    }
  },
  {
    title: '所属分类名称',
    dataIndex: 'catName',
    key: 'catName',
  },
  {
    title: '规格明细',
    dataIndex: 'normDetailInfo',
    key: 'normDetailInfo',
  },
  {
    title: '售价',
    dataIndex: 'shopPrice',
    key: 'shopPrice',
  },
  {
    title: '分销方案名称',
    dataIndex: 'distributionName',
    key: 'distributionName',
  },
  {
    title: '状态',
    dataIndex: 'distributionStatus',
    key: 'distributionStatus',
    render: (t) => <>{t == 2 ? '停用' : '启用'}</>
  },
];

const Single = props => {
  const { form } = props
  const { getFieldDecorator } = form
  const [data, setData] = useState([])
  const [names, setNames] = useState([])
  const [goods, setGoods] = useState([])
  const [brands, setBrands] = useState(null)
  const [distributionId, setDistributionId] = useState(null)
  const [totalPage, setTotalPage] = useState(null)
  const [visible, setVisible] = useState(false)
  const [record, setRecord] = useState([])
  const [param, setParam] = useState({
    catLv1Id: "",
    catLv2Id: "",
    goodsName: "",
    pageNo: 1,
    pageSize: 10,
  })

  useEffect(() => {
    init()
    getDistributeName()
    fetchGoodsCata()
  }, [])

  const init = async (params = param) => {
    const res = await getSingleList(params)
    setData(res.data)
    setTotalPage(res.total)
  }

  const getDistributeName = async () => {
    const res = await distributionPlanName()
    setNames(res.data)
  }

  const fetchGoodsCata = async (params = {
    resGoodsCat: {
      catParentId: 0,
    }
  }) => {
    const res = await goodsCatalog(params)
    setGoods(res.data)
  }

  const batchOperate = async records => {
    const params = []
    records.map(p => params.push({
      id: p.distributionGoodsRefId,
      status: p.distributionStatus == 1 ? '2' : '1',
      version: "1",
    }))
    const res = await startGoodsRef({distributionGoodsRefs: params})
    message.info(res.msg)
    init()
  }
  // 表单查询
  const handleSearch = e => {
    e.preventDefault()
    form.validateFields((err, values) => {
      console.log('Received values of form: ', values)
      const p = !brands ? { 'catLv2Id': values.catLv1Id } : null

      init({
        ...param,
        ...values,
        ...p,
      })
    })
  }
  // 表单清空
  const handleReset = e => {
    form.resetFields();
    init()
  }

  const handleGoodsList = val => {
    goodsCatalog({
      resGoodsCat: {
        catParentId: val
      }
    }).then(res => {
      setBrands(res.data)
    })
  }

  // 查询条件
  const getFields = () => {
    return(
      <>
        <Col span={6}>
          <Form.Item label={`商品分类`}>
            {getFieldDecorator(`catLv1Id`, {})
              (
              <Select onChange={handleGoodsList}>
                {
                  goods && goods.map(g => 
                    <Option key={g.id} value={g.id}>{g.catName}</Option>
                  )
                }
              </Select>
              )}
          </Form.Item>
        </Col>
        {brands && <Col span={6}>
          <Form.Item label={`商品品牌`}>
            {getFieldDecorator(`catLv2Id`, {})
              (<Select>
                {
                  brands.map(b =>
                    <Option key={b.id} value={b.id}>{b.catName}</Option>  
                  )
                }
              </Select>)}
          </Form.Item>
        </Col>}
        <Col span={6}>
          <Form.Item label={`商品名称`}>
            {getFieldDecorator(`goodsName`, {})
              (<Input />)}
          </Form.Item>
        </Col>
      </> 
    )
  }
  // 按钮处理
  const handleBtn = type => {
    if (record.length == 0) message.info('请选择一条数据')
    switch (type) {
      case 99:
        return batchOperate(record)
      case 98:
        return setVisible(!visible)
      default:
        break;
    }
  }

  const handleSettingName = () => {
    const params = []
    record.map(el => {
      params.push({
        distributionId,
        id: el.distributionGoodsRefId,
        goodsId: el.goodsId,
        status: el.distributionStatus,
      })
    })

    settingPlans({
      distributionGoodsRefs: params
    }).then(res => {
      message.warn(res.msg)
      init()
      setVisible(!visible)
    })
  }
  
  const pagination = {
    total: parseInt(totalPage),
    onChange(page) {
      init({
        ...param,
        pageNo: page,
      })
    }
  }
  const rowSelection = {
    type: 'checkbox',
    onChange: (selectedRowKeys, selectedRows) => {
      setRecord(selectedRows)
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
  };
  return (
    <PageHeaderWrapper>
      <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
      <RenderButtom click={handleBtn} />
      <Table 
        columns={columns}
        dataSource={hasSearchBtn ? data : []}
        rowSelection={rowSelection}
        rowKey={record => record.goodsId}
        pagination={pagination}
      />
      <Modal
        visible={visible}
        onCancel={() => setVisible(!visible)}
        onOk={handleSettingName}
        title='设置分销方案'
      >
        请选择分销方案： <Select style={{width: 300}} onChange={val => setDistributionId(val)}>
          {
            names && names.map(n =>
              <Option key={n.id} value={n.id}>{n.distributionName}</Option>
            )
          }
        </Select>
      </Modal>
    </PageHeaderWrapper>
    )
}

export default Form.create()(Single)
